//
//  PayViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/24.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyJSON

class PayViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,PayTableViewCellDelegate,UIPickerViewDelegate {

    var allPrice : String?
    
    var myTableView = UITableView(frame: CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT*0.8-64), style: .Grouped)
    
    let PAYTABLEVIEWCELL = "payTableViewCell"
    
    let imageArray = ["img_visa","img_mastercard","img_visa_debit","img_mastercard_debit","img_jcb"]
    
    let monthArray = ["1","2","3","4","5","6","7","8","9","10","11","12"]
    let yearArray = ["2016","2017","2018","2019","2020","2021","2022","2023","2024","2025","2026","2027","2028","2029","2030","2031"]
    
    let payBtn = UIButton(type: .Custom)

    
    var monthPickerView=UIPickerView()
    var yearPickerView=UIPickerView()
    
    var monthStr:String?
    var yearStr:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.creatNavView()
        self.creatTableView()
        self.creatPayNowView()
        self.creatPickerView()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
extension PayViewController{
    private func creatNavView(){
        
        self.view.backgroundColor = UIColor.whiteColor()
        self.automaticallyAdjustsScrollViewInsets = false
        self.title = "Payment Info"
        
        let leftBtn = UIButton(type: .Custom)
        leftBtn.setImage(UIImage(named: "nav_back"), forState: .Normal)
        leftBtn.frame = CGRectMake(0, 0, 30, 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), forControlEvents: .TouchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        
        
        let rightItemCustomeView   = UIButton(type: UIButtonType.Custom)
        rightItemCustomeView.frame = CGRectMake(0, 0, 30, 30)
        rightItemCustomeView.setImage(UIImage(named:"nav_close"), forState: UIControlState.Normal)
        rightItemCustomeView.addTarget(self, action: #selector(rightBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItemCustomeView);
        
        
    }
    
    func leftBtnClick(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    func rightBtnClick(){
        self.navigationController?.popToRootViewControllerAnimated(true)
    }
}


extension PayViewController{
    private func creatTableView(){
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        let nib = UINib(nibName: "PayTableViewCell", bundle: nil)
        
        myTableView.registerNib(nib, forCellReuseIdentifier: PAYTABLEVIEWCELL)
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 0
        }else{
            return 1
        }
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(PAYTABLEVIEWCELL)
        cell?.selectionStyle = .None
        (cell as? PayTableViewCell)?.delegate = self
        return cell!
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.whiteColor()
        
        if section == 0 {
            headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.08)
            
            let titleLabel = UILabel()
            titleLabel.frame = CGRectMake(20, SCREEN_HEIGHT*0.02, SCREEN_WIDTH*0.4, SCREEN_HEIGHT*0.06)
            titleLabel.text = "Order Total"
            titleLabel.font = UIFont.systemFontOfSize(15)
            headerView.addSubview(titleLabel)
            
            let priceLabel = UILabel()
            priceLabel.frame = CGRectMake(SCREEN_WIDTH*0.6-20, SCREEN_HEIGHT*0.02, SCREEN_WIDTH*0.4, SCREEN_HEIGHT*0.06)
            priceLabel.textAlignment = .Right
            priceLabel.text = self.allPrice!
            priceLabel.textColor = UIColor.redColor()
            priceLabel.font = UIFont.systemFontOfSize(15)
            headerView.addSubview(priceLabel)
            
            
        }else{
            headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.12)
            
            
            for i in 0..<imageArray.count {
                let imgView = UIImageView()
                let count = CGFloat(imageArray.count)
                let width = (SCREEN_WIDTH-20*(count+1))/count
                
                imgView.frame = CGRectMake(20+(20+width)*CGFloat(i), SCREEN_HEIGHT*0.02, width, SCREEN_HEIGHT*0.06)
                imgView.image = UIImage(named: self.imageArray[i])
                headerView.addSubview(imgView)
                
            }
            
        }
        
        return headerView
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 5
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return SCREEN_HEIGHT * 0.08
        }else{
            return SCREEN_HEIGHT * 0.1
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return SCREEN_HEIGHT * 0.4
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.monthPickerView.hidden = true
        self.yearPickerView.hidden = true
        self.view.endEditing(true)
    }
    
    
//    年月代理
    func monthDelegateToPayVC() {
        monthPickerView.hidden = false
        yearPickerView.hidden = true
    }
    func yearDelegateToPayVC() {
        monthPickerView.hidden = true
        yearPickerView.hidden = false
    }
}

extension PayViewController{
    private func creatPickerView(){
        
        monthPickerView.frame = CGRectMake(0, SCREEN_HEIGHT*0.7, SCREEN_WIDTH, SCREEN_HEIGHT*0.3)
        monthPickerView.delegate = self
        monthPickerView.backgroundColor = UIColor.whiteColor()
        monthPickerView.hidden = true
        monthPickerView.numberOfComponents
        self.view.addSubview(monthPickerView)
        
        yearPickerView.frame = CGRectMake(0, SCREEN_HEIGHT*0.7, SCREEN_WIDTH, SCREEN_HEIGHT*0.3)
        yearPickerView.delegate = self
        yearPickerView.backgroundColor = UIColor.whiteColor()
        yearPickerView.hidden = true
        self.view.addSubview(yearPickerView)
        
    }
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
        return 1
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        if pickerView == monthPickerView {
            return monthArray.count
        }else{
            return yearArray.count
        }
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView == monthPickerView {
            return monthArray[row]
        }else{
            return yearArray[row]
        }
    }
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let indexPath = NSIndexPath(forRow: 0, inSection: 1)
        let cell = self.myTableView.cellForRowAtIndexPath(indexPath) as? PayTableViewCell
        let monthBtn = cell?.monthBtn
        let yearBtn = cell?.yearBtn
        
        if pickerView == monthPickerView {
            monthPickerView.hidden = true
            monthBtn?.setTitle(monthArray[row], forState: .Normal)
            monthStr = monthArray[row]
            self.myTableView.reloadData()
        }else{
            yearPickerView.hidden = true
            yearBtn?.setTitle(yearArray[row], forState: .Normal)
            yearStr = yearArray[row]
            self.myTableView.reloadData()
        }
    }
    
}

extension PayViewController{
    private func creatPayNowView(){
        let payView = UIView()
        payView.frame = CGRectMake(0, SCREEN_HEIGHT*0.8, SCREEN_WIDTH, SCREEN_HEIGHT*0.2)
        payView.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(payView)
        
        payBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.07)
        payBtn.setTitle("PAY NOW", forState: .Normal)
        payBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        payBtn.addTarget(self, action: #selector(addBtnClick(_:)), forControlEvents: .TouchUpInside)
        payBtn.backgroundColor = UIColor.blackColor()
        payView.addSubview(payBtn)
        
        let iconImageView = UIImageView()
        iconImageView.frame = CGRectMake(20, SCREEN_HEIGHT*0.09, SCREEN_HEIGHT*0.09, SCREEN_HEIGHT*0.09)
        iconImageView.image = UIImage(named: "img_guarantee")
        payView.addSubview(iconImageView)
        
        let label = UILabel()
        label.frame = CGRectMake(30+SCREEN_HEIGHT*0.09, SCREEN_HEIGHT*0.09, SCREEN_WIDTH-SCREEN_HEIGHT*0.09-50, SCREEN_HEIGHT*0.09)
        label.font = UIFont.systemFontOfSize(14)
        label.numberOfLines = 0
        label.text = "We will not save your credit information trusted by over one million shoppers in 50 countries."
        payView.addSubview(label)
        
        
    }
    
    func addBtnClick(button:UIButton){
        let indexPath = NSIndexPath(forRow: 0, inSection: 1)
        let cell = self.myTableView.cellForRowAtIndexPath(indexPath) as! PayTableViewCell
        
        if button.selected == true {
            SVProgressHUD.showInfoWithStatus("Please click pay button after 5 seconds!")
            return
        }else{
            button.selected = true
            
            self.performSelector(#selector(buttonSelected(_:)), withObject: nil, afterDelay: 5.0)
            
            if self.judgeCanSave() == "" {
                
                let urlStr = APIBASE + "main_page=checkout_confirmation"
                let parma = ["Cp_Num":cell.CardTextField.text!,
                             "Cp_CVV":cell.CVCTextField.text!,
                             "Cp_ExpireMonth":monthStr!,
                             "Cp_ExpireYear":yearStr!,
                             "zenid":UserSession.shareInstance.cookie!]
                
                NetworkTool.shareInstance.request(.POST, urlString: urlStr, parmas: parma, finishedBlock: { (result, error) in
                    if result != nil{
                        let currency = NSUserDefaults.standardUserDefaults().objectForKey("CURRENCY")
                        let dic = result as? NSDictionary
                        let number = String(dic!["status"]!)
                        print(number)
                        if number == "1"{
                            
                            MobClick.event("PayNowClick", attributes: ["email":UserSession.shareInstance.email!,"currency" : (currency as? String)!,"money":self.allPrice!,"status":"The payment information fill out successfully!"])

                            
                            SVProgressHUD.showSuccessWithStatus("The payment information fill out successfully!")
                            self.navigationController?.popToRootViewControllerAnimated(true)
                        }else{

                            MobClick.event("PayNowClick", attributes: ["email":UserSession.shareInstance.email!,"currency" : (currency as? String)!,"money":self.allPrice!,"status":String(dic!["status_message"])])
                            SVProgressHUD.showInfoWithStatus(String(dic!["status_message"]))
                        }
                    }else{
                        SVProgressHUD.showErrorWithStatus("paynow error:" + String(error))
                        print("payNow error:" + String(error))
                    }
                })
                
            }else{
                SVProgressHUD.showInfoWithStatus(self.judgeCanSave())
            }

        }
        
        
    }
    
    func buttonSelected(button:UIButton){
        payBtn.selected = false
    }
    
    
    func judgeCanSave() -> String{
        
        let indexPath = NSIndexPath(forRow: 0, inSection: 1)
        let cell = self.myTableView.cellForRowAtIndexPath(indexPath) as? PayTableViewCell
        
        if cell?.CardTextField.text == nil || cell?.CardTextField.text == "" {
            return "Bank card number cannot be empty!"
        }
        if  cell?.CVCTextField.text == nil || cell?.CVCTextField.text == ""{
            return "CVV cannot be empty!"
        }
        if monthStr == nil || monthStr == "" {
            return "Month cannot be empty!"
        }
        if yearStr == nil || yearStr == "" {
            return "Year cannot be empty!"
        }
        
        return ""
        
    }
}














